package com.stadium.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.stadium.common.utils.SqlMapper;
import com.stadium.common.utils.UserUtils;
import com.stadium.dto.BasicsRecordDto;
import com.stadium.dto.GameScheduleDto;
import com.stadium.dto.StarterDto;
import com.stadium.dto.SysUserDto1;
import com.stadium.entity.BasicsRecord;
import com.stadium.entity.GameSchedule;
import com.stadium.entity.RecordStatistical;
import com.stadium.mapper.BasicsRecordMP;
import com.stadium.mapper.GameScheduleMP;
import com.stadium.mapper.RTeamUserMP;
import com.stadium.mapper.RecordStatisticalMP;
import com.stadium.service.BasicsRecordSV;
import com.stadium.vo.BasicsRecordVo;
import com.stadium.vo.ScheduleRecordVo;
import com.stadium.vo.searchVo.BasicsRecordSearchVo;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class BasicsRecordSVI implements BasicsRecordSV {
    @Autowired
    private BasicsRecordMP mapper;
    @Autowired
    private SqlMapper sqlMapper;
    @Autowired
    private RecordStatisticalMP recordStatisticalMP;
    @Autowired
    private GameScheduleMP gameScheduleMP;
    @Autowired
    private RTeamUserMP rTeamUserMP;

    @Override
    public List<BasicsRecord> queryBySQL(String sql, Map<String, Object> map) {
        return sqlMapper.selectList(sql, map, BasicsRecord.class);
    }

    @Override
    public void save(ScheduleRecordVo scheduleRecordVo) {
        saveBatch(scheduleRecordVo);
        this.saveTeamScore(scheduleRecordVo);
    }

    private void saveTeamScore(ScheduleRecordVo scheduleRecordVo) {
        GameScheduleDto gameScheduleDto = gameScheduleMP.get(scheduleRecordVo.getBasicsRecordList().get(0).getScheduleId());
        BasicsRecordSearchVo basicsRecordsearchVo = new BasicsRecordSearchVo();
        basicsRecordsearchVo.setScheduleId(gameScheduleDto.getId());
        basicsRecordsearchVo.setTeamId(gameScheduleDto.getHometeamId());
        basicsRecordsearchVo.setCode("22");
        int homeTeamScore = this.getTeamScore(basicsRecordsearchVo);
        basicsRecordsearchVo.setTeamId(gameScheduleDto.getGuestteamId());
        int guestTeamScore = this.getTeamScore(basicsRecordsearchVo);
        GameSchedule gameSchedule = new GameSchedule();
        gameSchedule.setUpdateUser(UserUtils.getUserId());
        gameSchedule.setHometeamScore(homeTeamScore);
        gameSchedule.setGuestteamScore(guestTeamScore);
        gameSchedule.setId(gameScheduleDto.getId());
        gameScheduleMP.update(gameSchedule);
    }

    @Override
    public void update(BasicsRecordVo basicsRecordVo) {
        BasicsRecord basicsRecord = new BasicsRecord();
        BeanUtils.copyProperties(basicsRecordVo, basicsRecord);
        basicsRecord.setUpdateUser(UserUtils.getUserId());
        mapper.update(basicsRecord);
    }

    @Override
    public void saveBatch(ScheduleRecordVo scheduleRecordVo) {
        List<BasicsRecord> basicsRecordList = scheduleRecordVo.getBasicsRecordList();
        basicsRecordList.stream().forEach(basicsRecord -> {
            basicsRecord.setEventId(scheduleRecordVo.getEventId());
            if (scheduleRecordVo.getScheduleId() != null) {
                basicsRecord.setScheduleId(scheduleRecordVo.getScheduleId());
            }
            basicsRecord.setUpdateUser(UserUtils.getUserId());
            basicsRecord.setCreateUser(UserUtils.getUserId());
        });
        mapper.saveBatch(basicsRecordList);
        this.saveStatistical(basicsRecordList);
    }


    public void saveStatistical(List<BasicsRecord> basicsRecordList){
        List<RecordStatistical> list = new ArrayList<>();
        Map<String, List<BasicsRecord>> collect = basicsRecordList.stream().collect(Collectors.groupingBy(basicsRecord -> basicsRecord.getTeamId() + '-' + basicsRecord.getUserId() + '-' + basicsRecord.getCode()));
        for (List<BasicsRecord> basicsRecords : collect.values()) {
            RecordStatistical recordStatistical = new RecordStatistical();
            BeanUtils.copyProperties(basicsRecords.get(0), recordStatistical);
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            recordStatistical.setCreateUser(UserUtils.getUserId());
            recordStatistical.setUpdateUser(UserUtils.getUserId());
            recordStatistical.setId(id);
            String code = basicsRecords.get(0).getCode();
            if ("21".equals(code) || "22".equals(code) || "20".equals(code)|| "23".equals(code)){
                recordStatistical.setNumber(basicsRecords.get(0).getScore());
            }else {
                recordStatistical.setNumber(basicsRecords.size());
            }
            list.add(recordStatistical);
        }
        recordStatisticalMP.saveBatch(list);
    }

    @Override
    public void delete(String id) {
        mapper.delete(id);
    }

    @Override
    public void deleteBatch(String[] ids) {
        mapper.deleteBatch(ids);
    }

    @Override
    public List<BasicsRecordDto> query(BasicsRecordSearchVo searchVo) {
        return mapper.query(searchVo);
    }

    @Override
    public BasicsRecordDto get(String id) {
        return mapper.get(id);
    }

    @Override
    public int getCount(BasicsRecordSearchVo searchVo) {
        return mapper.getCount(searchVo);
    }

    @Override
    public int getTeamScore(BasicsRecordSearchVo basicsRecordsearchVo) {
        return mapper.getTeamScore(basicsRecordsearchVo);
    }

    @Override
    public List<StarterDto> getStarter(BasicsRecordSearchVo basicsRecordSearchVo) {
        List<BasicsRecordDto> starterDtoList = mapper.getStarter(basicsRecordSearchVo);
        List<SysUserDto1> teamUsers = rTeamUserMP.getPlayersByTeamId(basicsRecordSearchVo.getTeamId());
        List<StarterDto> starterDtos = new ArrayList<>(teamUsers.size());
        int order =0;
        if (teamUsers != null) {
            for (SysUserDto1 sysUserDto1 : teamUsers) {
                StarterDto starterDto = new StarterDto();
                BeanUtils.copyProperties(sysUserDto1,starterDto);
                starterDto.setIsStarter(false);
                starterDto.setOrder(999);
                for (BasicsRecordDto basicsRecordDto: starterDtoList) {
                    if(basicsRecordDto.getUserId().equals(sysUserDto1.getId())){
                        starterDto.setIsStarter(true);
                        starterDto.setOrder(++order);
                    }
                }
                starterDtos.add(starterDto);
            }
        }
        starterDtos.stream().sorted(Comparator.comparing(StarterDto::getOrder).reversed()).collect(Collectors.toList());
        return starterDtos;
    }

}
